package com.xianyuwangyou.taizhangdengji

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.xianyuwangyou.taizhangdengji.ui.theme.TaizhangdengjiTheme

class SplashActivity : ComponentActivity() {
    private val handler = Handler(Looper.getMainLooper())
    private val splashDelay = 3000L // 3秒延迟
    private var mainActivityIntent: Intent? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 在启动图展示期间预加载主页面数据
        preloadMainActivity()
        
        setContent {
            TaizhangdengjiTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    SplashScreen(onSkip = {
                        // 移除延迟跳转的回调并立即跳转
                        handler.removeCallbacksAndMessages(null)
                        navigateToMain()
                    })
                }
            }
        }
    }
    
    /**
     * 在启动图展示期间预加载主页面
     */
    private fun preloadMainActivity() {
        // 预先创建MainActivity的Intent，这会触发系统对MainActivity的预加载
        mainActivityIntent = Intent(this@SplashActivity, MainActivity::class.java)
        
        // 在后台线程中预加载主页面所需的数据
        Thread {
            try {
                // 初始化AppInitializer
                val appInitializer = AppInitializer()
                appInitializer.initializeAppData(this)
                
                // 初始化并加载数据
                val dataManager = AccountDataManager.getInstance()
                dataManager.loadAccountData(this) // 使用改进的加载方法
                
                // 初始化并加载配置数据
                val configDataManager = ConfigDataManager.getInstance()
                configDataManager.loadConfigData(this)
                
                // 发送广播通知数据加载完成
                val intent = Intent("com.xianyuwangyou.taizhangdengji.DATA_LOADED")
                sendBroadcast(intent)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }.start()
    }
    
    private fun navigateToMain() {
        try {
            // 使用预先创建的Intent，如果不存在则创建新的
            val intent = mainActivityIntent ?: Intent(this@SplashActivity, MainActivity::class.java)
            startActivity(intent)
            finish() // 关闭当前Activity
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    override fun onResume() {
        super.onResume()
        // 延迟跳转到主Activity
        handler.postDelayed({
            navigateToMain()
        }, splashDelay)
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 移除未执行的回调，防止内存泄漏
        handler.removeCallbacksAndMessages(null)
    }
}

@Composable
fun SplashScreen(onSkip: () -> Unit) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White),
        contentAlignment = Alignment.Center
    ) {
        // 使用专业设计的启动页图片
        Image(
            painter = painterResource(id = R.drawable.start),
            contentDescription = "启动页",
            modifier = Modifier.fillMaxSize(),
            contentScale = androidx.compose.ui.layout.ContentScale.Crop
        )
        
        // 跳过按钮
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            Button(
                onClick = onSkip,
                modifier = Modifier
                    .align(Alignment.TopEnd)
                    .padding(16.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color.Black.copy(alpha = 0.5f),
                    contentColor = Color.White
                )
            ) {
                Text(
                    text = "跳过",
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Normal
                )
            }
        }
    }
}